"""
FastAPI任务调度系统主应用
整合所有模块，提供统一的应用入口
"""

from contextlib import asynccontextmanager
from pathlib import Path
import sys

from loguru import logger
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

# 导入应用模块
from app.api.routes import router as api_router
from app.services.task_service import task_manager
from app.core.sse_manager import sse_manager

# 导入示例任务函数
from examples.demo_tasks import *


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时
    logger.info("正在启动任务调度系统...")
    try:
        await task_manager.start()
        yield
    finally:
        # 关闭时
        logger.info("正在关闭任务调度系统...")
        try:
            await task_manager.stop()
            await sse_manager.shutdown()
            logger.info("任务调度系统已停止")
        except Exception as e:
            logger.error(f"关闭过程中出错: {e}")


# 创建 FastAPI 应用
app = FastAPI(
    title="任务调度系统",
    description="基于FastAPI和AsyncIO的高性能任务调度系统",
    version="2.0.0",
    lifespan=lifespan,
)

# 设置模板目录
templates = Jinja2Templates(directory="templates")

# 配置静态文件服务
static_path = Path("static")
if static_path.exists():
    app.mount("/static", StaticFiles(directory="static"), name="static")

# 注册API路由
app.include_router(api_router, prefix="/api/v1")


@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
    """首页 - 任务管理界面"""
    return templates.TemplateResponse("index.html", {"request": request})


@app.get("/health")
async def health_check():
    """健康检查端点"""
    return {
        "status": "healthy",
        "service": "任务调度系统",
        "version": "2.0.0",
        "connections": sse_manager.get_clients_count(),
    }


if __name__ == "__main__":
    import uvicorn

    # 直接运行，使用默认配置
    uvicorn.run(app, host="0.0.0.0", port=8001)
